package com.jiulan.hearthearing.ui.my.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseActivity;
import com.jiulan.hearthearing.base.BaseModel;
import com.jiulan.hearthearing.common.UserData;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.my.model.UploadImageModel;
import com.jiulan.hearthearing.ui.my.view.PersonInfoSetDialog;
import com.jiulan.hearthearing.ui.my.view.PersonInfoNickNameDialog;
import com.jiulan.hearthearing.utils.ImageCompress;
import com.jiulan.hearthearing.utils.TimeUtils;
import com.jiulan.hearthearing.widget.PhotoPickBottomDialog;
import com.shehuan.niv.NiceImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PersonInfoActivity extends BaseActivity implements View.OnClickListener {
    private File file = new File(Environment.getExternalStorageDirectory().getPath());
    private static final int REQUEST_CODE = 10;
    private String avatar = "";//头像
    private String nickname = "";//昵称
    private String real_name = "";//真实姓名
    private int sex;//性别 1男 2女
    private String card_id = "";//身份证号
    private String person_sign = "";//个人签名
    private String school = "";//学历
    private String profession = "";//行业
    private String work = "";//职业
    private String birthday = "";//出生日期 2012-025-05
    private List<String> schoolList;
    private List<String> professionList;
    private List<String> workList;

    private NiceImageView nivPhoto;
    private TextView tvNickname;
    private TextView tvQianming;
    private ImageView ivMan;
    private ImageView ivWoman;
    private TextView tvBirthYear;
    private TextView tvXueli;
    private TextView tvHangye;
    private TextView tvZhiye;
    private TextView tvSave;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, PersonInfoActivity.class);
        context.startActivity(intent);
    }

    public static LocalBroadcastManager localBroadcastManager;
    private MyBroadcastReceiver myBroadcastReceiver;
    private IntentFilter filter;
    public static String LOCAL_BROADCAST = "com.jiulan.hearthearing.ui.my.activity.PersonInfoActivity";

    public void registerMessageReceiver() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        myBroadcastReceiver = new MyBroadcastReceiver();
        filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(LOCAL_BROADCAST);
        localBroadcastManager.registerReceiver(myBroadcastReceiver, filter);
    }

    public class MyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (LOCAL_BROADCAST.equals(intent.getAction())) {
                    switch (intent.getIntExtra("action", 1)) {
                        case 1://学历
                            school = intent.getStringExtra("value");
                            tvXueli.setText(school);
                            break;
                        case 2://行业
                            profession = intent.getStringExtra("value");
                            tvHangye.setText(profession);
                            break;
                        case 3://职业
                            work = intent.getStringExtra("value");
                            tvZhiye.setText(work);
                            break;
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_person_info;
    }

    @Override
    protected void initView() {
        setTitleText("编辑资料");
        registerMessageReceiver();
        nivPhoto = findViewById(R.id.nivPhoto);
        tvNickname = findViewById(R.id.tvNickname);
        tvQianming = findViewById(R.id.tvQianming);
        ivMan = findViewById(R.id.ivMan);
        ivWoman = findViewById(R.id.ivWoman);
        tvBirthYear = findViewById(R.id.tvBirthYear);
        tvXueli = findViewById(R.id.tvXueli);
        tvHangye = findViewById(R.id.tvHangye);
        tvZhiye = findViewById(R.id.tvZhiye);
        tvSave = findViewById(R.id.tvSave);
        nivPhoto.setOnClickListener(this);
        tvNickname.setOnClickListener(this);
        tvQianming.setOnClickListener(this);
        ivMan.setOnClickListener(this);
        ivWoman.setOnClickListener(this);
        tvBirthYear.setOnClickListener(this);
        tvXueli.setOnClickListener(this);
        tvHangye.setOnClickListener(this);
        tvZhiye.setOnClickListener(this);
        tvSave.setOnClickListener(this);
        setView();
        setData();
    }

    private void setData() {
        schoolList = new ArrayList<>();
        schoolList.add("高中及以下");
        schoolList.add("专科");
        schoolList.add("本科");
        schoolList.add("研究生");
        schoolList.add("博士及以上");
        professionList = new ArrayList<>();
        professionList.add("互联网");
        professionList.add("IT");
        professionList.add("制造业");
        professionList.add("金融");
        professionList.add("教育");
        professionList.add("医药医疗");
        professionList.add("建筑房地产");
        professionList.add("传媒");
        professionList.add("政府机关");
        workList = new ArrayList<>();
        workList.add("学生");
        workList.add("创业者");
        workList.add("程序员");
        workList.add("工程师");
        workList.add("销售");
        workList.add("运营");
        workList.add("企业老板");
        workList.add("中高层管理者");
        workList.add("普通白领");
        workList.add("公务员");
        workList.add("事业单位员工");
    }

    private void setView() {
        avatar = UserData.create().get(UserData.AVATAR);//头像
        nickname = UserData.create().get(UserData.NICKNAME);//昵称
        real_name = UserData.create().get(UserData.REALNAME);//真实姓名
        sex = UserData.create().get(UserData.SEX, 1);//性别 1男 2女
        card_id = UserData.create().get(UserData.CARDID);//身份证号
        person_sign = UserData.create().get(UserData.PERSONSIGN);//个人签名
        school = UserData.create().get(UserData.SCHOOL);//学历
        profession = UserData.create().get(UserData.PROFESSION);//行业
        work = UserData.create().get(UserData.WORK);//职业
        birthday = UserData.create().get(UserData.BIRTHDAY);//出生日期 2012-025-05
        Glide.with(getContext()).load(avatar).into(nivPhoto);
        tvNickname.setText(nickname);
        tvQianming.setText(person_sign);
        tvBirthYear.setText(birthday);
        tvXueli.setText(school);
        tvHangye.setText(profession);
        tvZhiye.setText(work);
        setSex(sex);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected int getTitleBarType() {
        return TITLEBAR_DEFAULT;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.nivPhoto:
                PhotoPickBottomDialog photoPickBottomDialog = new PhotoPickBottomDialog();
                photoPickBottomDialog.setClicklistener(new PhotoPickBottomDialog.ClickListenerInterface() {
                    @Override
                    public void takePhoto() {
                        //拍照并剪裁
                        ImageSelector.builder()
                                .setCrop(true) // 设置是否使用图片剪切功能。
                                .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
                                .onlyTakePhoto(true)  // 仅拍照，不打开相册
                                .start(PersonInfoActivity.this, REQUEST_CODE);
                    }

                    @Override
                    public void selectFromAlbum() {
                        //单选并剪裁
                        ImageSelector.builder()
                                .useCamera(true) // 设置是否使用拍照
                                .setCrop(true)  // 设置是否使用图片剪切功能。
                                .setCropRatio(1.0f) // 图片剪切的宽高比,默认1.0f。宽固定为手机屏幕的宽。
                                .setSingle(true)  //设置是否单选
                                .canPreview(true) //是否可以预览图片，默认为true
                                .start(PersonInfoActivity.this, REQUEST_CODE); // 打开相册
                    }
                });
                photoPickBottomDialog.show(getSupportFragmentManager());
                break;
            case R.id.tvNickname:
                final PersonInfoNickNameDialog nickNameDialog = new PersonInfoNickNameDialog(getContext(), "编辑昵称", "");
                nickNameDialog.setClicklistener(new PersonInfoNickNameDialog.ClickListenerInterface() {
                    @Override
                    public void doCancel() {
                        nickNameDialog.dismiss();
                    }

                    @Override
                    public void doConfirm(String content) {
                        nickNameDialog.dismiss();
                        nickname = content;
                        tvNickname.setText(nickname);
                    }
                });
                nickNameDialog.show();
                break;
            case R.id.tvQianming:
                final PersonInfoNickNameDialog qianmingDialog = new PersonInfoNickNameDialog(getContext(), "编辑个性签名", "");
                qianmingDialog.setClicklistener(new PersonInfoNickNameDialog.ClickListenerInterface() {
                    @Override
                    public void doCancel() {
                        qianmingDialog.dismiss();
                    }

                    @Override
                    public void doConfirm(String content) {
                        qianmingDialog.dismiss();
                        person_sign = content;
                        tvQianming.setText(person_sign);
                    }
                });
                qianmingDialog.show();
                break;
            case R.id.ivMan:
                sex = 1;
                setSex(1);
                break;
            case R.id.ivWoman:
                sex = 2;
                setSex(2);
                break;
            case R.id.tvBirthYear:// .setDate(birthday)// 如果不设置的话，默认是系统时间*/
                setBirthday();
                break;
            case R.id.tvXueli:
                PersonInfoSetDialog dialog = new PersonInfoSetDialog(getContext(), 1, schoolList, school);
                dialog.show(getSupportFragmentManager());
                break;
            case R.id.tvHangye:
                PersonInfoSetDialog dialog1 = new PersonInfoSetDialog(getContext(), 2, professionList, profession);
                dialog1.show(getSupportFragmentManager());
                break;
            case R.id.tvZhiye:
                PersonInfoSetDialog dialog2 = new PersonInfoSetDialog(getContext(), 3, workList, work);
                dialog2.show(getSupportFragmentManager());
                break;
            case R.id.tvSave:
                save();
                break;
        }
    }

    private void checkPermission() {

        if (Build.VERSION.SDK_INT >= 23) {
            int write = checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int read = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
            if (write != PackageManager.PERMISSION_GRANTED || read != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 300);
            } else {
                String name = "CrashDirectory";
                File file1 = new File(Environment.getExternalStorageDirectory(), name);
            }
        } else {
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 300) {

        } else {

        }
    }

    private void setBirthday() {
        //时间选择器
        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                birthday = TimeUtils.getDateStr(date, "yyyy-MM-dd");
                tvBirthYear.setText(birthday);
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(18)//标题文字大小
//                .setTitleText(getString(R.string.birthday))//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
//                .setTitleColor(getResources().getColor(R.color.black_light))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.gray6))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.title_bg))//取消按钮文字颜色
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设���为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的 label 文字，false 则每项 item 全部都带有 label。
                .build();
        pvTime.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            //获取选择器返回的数据
            ArrayList<String> images = data.getStringArrayListExtra(
                    ImageSelector.SELECT_RESULT);
            Bitmap bmp = BitmapFactory.decodeFile(images.get(0));
            File cropfile = new File(file, System.currentTimeMillis() + "headPhoto.jpg");
            ImageCompress.qualityCompress(bmp, cropfile);
            modifyPhoto(cropfile);
        }
    }

    private void modifyPhoto(File cropfile) {
        new HttpRequest(getContext()).doUploadFile(UrlConstants.upload_image, "", "file", cropfile, UploadImageModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof UploadImageModel) {
                    UploadImageModel model = (UploadImageModel) result;
                    avatar = model.getData().getUrl();
                    Glide.with(getContext()).load(avatar).into(nivPhoto);
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    /**
     * 设置个人信息
     */
    private void save() {
        Map<String, String> map = new HashMap<>();
        map.put("nickname", nickname);
        map.put("real_name", real_name);
        map.put("sex", String.valueOf(sex));
        map.put("card_id", card_id);
        map.put("person_sign", person_sign);
        map.put("school", school);
        map.put("profession", profession);
        map.put("work", work);
        map.put("birthday", birthday);
        new HttpRequest(getContext()).doPost(UrlConstants.user_edit, "", map, BaseModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof BaseModel) {
                    BaseModel model = (BaseModel) result;
                    if (model.getStatus() == 200) {
                        UserData.create().changeUserData(UserData.AVATAR, avatar);
                        UserData.create().changeUserData(UserData.NICKNAME, nickname);
                        UserData.create().changeUserData(UserData.REALNAME, real_name);
                        UserData.create().changeUserData(UserData.SEX, sex);
                        UserData.create().changeUserData(UserData.CARDID, card_id);
                        UserData.create().changeUserData(UserData.PERSONSIGN, person_sign);
                        UserData.create().changeUserData(UserData.SCHOOL, school);
                        UserData.create().changeUserData(UserData.PROFESSION, profession);
                        UserData.create().changeUserData(UserData.WORK, work);
                        UserData.create().changeUserData(UserData.BIRTHDAY, birthday);

                    } else {
                        Toast.makeText(getContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {

            }
        });
    }

    private void setSex(int value) {
        if (value == 1) {
            ivMan.setImageResource(R.mipmap.select);
            ivWoman.setImageResource(R.mipmap.unselect);
        } else if (value == 2) {
            ivMan.setImageResource(R.mipmap.unselect);
            ivWoman.setImageResource(R.mipmap.select);
        }
    }
}
